import { ClassConstructor, GetTypeOf, TypeClassConstructor } from "../../../Decorator/Decorator";
import { Queue } from "../../../Support/Share/Lib/Collections/Queue";
import { Dictionary } from "../../../Support/Share/Lib/Dictionary";
import { NamedObject } from "../../Object/NamedObject";
import { Singleton } from "../../Singleton/Singleton";

export class ObjectPool extends Singleton<ObjectPool> {

    private static _Instance: ObjectPool;
    static get Instance() {
        return this._Instance;
    }

    protected set Instance(value: ObjectPool) {
        ObjectPool._Instance = value;
    }

    private readonly pool: Dictionary<string, Queue<object>> = new Dictionary<string, Queue<object>>();

    public Fetch<T>(typeClazz: TypeClassConstructor<T>): T {
        let type = GetTypeOf(typeClazz);
        let queue = this.pool.TryGetValue(type);
        if (!queue) {
            return new typeClazz();
        }
        if (queue.Count === 0) {
            return new typeClazz();
        }
        return queue.Dequeue() as T;
    }

    public Recycle(obj: Object): void {
        let type = GetTypeOf(obj);
        let queue = this.pool.TryGetValue(type);
        if (!queue) {
            queue = new Queue<object>();
            this.pool.Add(type, queue);
        }
        //一种对象最大为1000个
        if (queue.Count > 1000) {
            return;
        }
        queue.Enqueue(obj);
    }

}